// MainUI.ts - 主界面控制脚本
import { _decorator, Component, Node, Sprite, Label, Button, Prefab, instantiate, tween, Vec3 } from 'cc';
import { GameDataService } from './GameDataService';
const { ccclass, property } = _decorator;

@ccclass('MainUI')
export class MainUI extends Component {
    @property({ type: Prefab })
    rewardPopupPrefab: Prefab | null = null; // 奖励弹窗预制体

    @property({ type: Node })
    chestNode: Node | null = null; // 宝箱节点

    @property({ type: Label })
    keyCountLabel: Label | null = null; // 钥匙数量文本

    @property({ type: Label })
    goldLabel: Label | null = null;  // 金币节点

    @property({ type: Label })
    diamondLabel: Label | null = null; // 钻石节点

    @property({ type: Label })
    powerLabel: Label | null = null; // 战力节点

    @property({ type: Label })
    titleLabel: Label | null = null; // 爵位节点

    @property({ type: Sprite })
    avatarSprite: Sprite | null = null; // 头像节点

    @property({ type: Prefab })
    bagPanelPrefab: Prefab | null = null; // 新增：包裹界面预制体

    private keyCount: number = 5; // 初始钥匙数量
    private dataService: GameDataService;

    onLoad() {
        this.dataService = GameDataService.getInstance();
        console.log("MainUI加载完成");
    }

    start() {
        this.updateKeyCountDisplay();
        this.updatePlayerInfoDisplay();
        this.autoBindButtonEvents();

        // 测试数据操作
        this.testDataOperations();
    }

    // 更新玩家信息显示
    updatePlayerInfoDisplay() {
        const playerInfo = this.dataService.getPlayerInfo();
        
        if (this.goldLabel) this.goldLabel.string = playerInfo.gold.toString();
        if (this.diamondLabel) this.diamondLabel.string = playerInfo.diamond.toString();
        if (this.powerLabel) this.powerLabel.string = playerInfo.power.toString();
        if (this.titleLabel) this.titleLabel.string = playerInfo.title;
        
        // 这里可以加载头像资源
        // this.loadAvatar(playerInfo.avatar);
    }

    // 更新钥匙数量显示
    updateKeyCountDisplay() {
        if (this.keyCountLabel) {
            this.keyCountLabel.string = `×${this.keyCount}`;
        }
    }

    // 测试数据操作
    testDataOperations() {
        console.log("玩家信息:", this.dataService.getPlayerInfo());
        console.log("装备信息:", this.dataService.getEquipment());
        console.log("背包物品:", this.dataService.getInventory());
        console.log("宠物列表:", this.dataService.getPets());
        console.log("坐骑列表:", this.dataService.getMounts());

        // 添加一些金币测试
        this.dataService.addGold(500);
        this.updatePlayerInfoDisplay();
    }

    // 开宝箱按钮回调
    onOpenChest() {
        console.log("开宝箱按钮回调")
        // 检查是否有足够的钥匙
        if (this.keyCount <= 0) {
            console.log("钥匙不足");
            return;
        }

        // 扣除钥匙
        this.keyCount--;
        this.updateKeyCountDisplay();

        // 播放宝箱抖动动画
        this.playChestAnimation();

        // 延迟显示奖励弹窗
        this.scheduleOnce(() => {
            this.showRewardPopup();

            // 开宝箱获得奖励
            this.dataService.addGold(100); // 获得100金币
            this.dataService.addToInventory({
                id: "item_" + Date.now(),
                type: "material",
                name: "宝箱奖励",
                count: 1,
                maxStack: 10,
                value: 50
            });
            this.updatePlayerInfoDisplay();
        }, 0.8);
    }

    // 宝箱抖动动画
    playChestAnimation() {
        console.log("this.chestNode = ", this.chestNode)
        if (!this.chestNode) return;

        const originalPos = this.chestNode.position.clone();

        tween(this.chestNode)
            .to(0.1, { position: new Vec3(originalPos.x + 15, originalPos.y, originalPos.z) })
            .to(0.1, { position: new Vec3(originalPos.x - 15, originalPos.y, originalPos.z) })
            .to(0.1, { position: new Vec3(originalPos.x + 10, originalPos.y, originalPos.z) })
            .to(0.1, { position: new Vec3(originalPos.x - 10, originalPos.y, originalPos.z) })
            .to(0.1, { position: originalPos })
            .start();
    }

    // 显示奖励弹窗
    showRewardPopup() {
        if (!this.rewardPopupPrefab) return;

        const rewardPopup = instantiate(this.rewardPopupPrefab);
        this.node.addChild(rewardPopup);

        // 点击任意位置关闭弹窗
        const closeBtn = rewardPopup.getChildByName('CloseArea');
        if (closeBtn) {
            closeBtn.on(Button.EventType.CLICK, () => {
                rewardPopup.destroy();
            }, this);
        }
    }

    // 其他按钮回调函数
    onBagClick() {
        console.log("打开背包");
        // const inventory = this.dataService.getInventory();
        // console.log("背包内容:", inventory);
        
        // 这里可以打开背包UI，显示物品列表
        this.showBagPanel();
    }

    // 显示包裹界面
    showBagPanel() {
        console.log("尝试打开包裹界面");
        console.log("bagPanelPrefab:", this.bagPanelPrefab);
        
        if (!this.bagPanelPrefab) {
            console.error("BagPanel预制体未设置 - 请在编辑器中拖拽BagPanel.prefab到MainUI组件的bagPanelPrefab属性");
            return;
        }

        // 检查是否已经存在包裹界面
        const existingPanel = this.node.children.find(child => child.name === 'BagPanel');
        if (existingPanel) {
            console.log("包裹界面已存在，先销毁旧的");
            existingPanel.destroy();
        }

        try {
            const bagPanel = instantiate(this.bagPanelPrefab);
            if (!bagPanel) {
                console.error("实例化BagPanel失败");
                return;
            }

            bagPanel.name = 'BagPanel';
            this.node.addChild(bagPanel);
            
            // 设置位置确保显示在顶层
            bagPanel.setPosition(0, 0, 0);
            console.log("✅ 包裹界面创建成功");

        } catch (error) {
            console.error("创建包裹界面时出错:", error);
        }
    }

    closeAllPanels() {
        const panels = this.node.children.filter(child => 
            child.name === 'BagPanel' || child.name.includes('Panel')
        );
        panels.forEach(panel => {
            if (panel.isValid) {
                panel.destroy();
            }
        });
    }

    onHomeClick() {
        console.log("返回主界面");
    }

    onReformClick() {
        console.log("打开改造界面");
    }

    // 左上角功能按钮
    onRankClick() {
        console.log("打开排行榜");
    }

    onPKClick() {
        console.log("打开PK榜");
    }

    onMailClick() {
        console.log("打开邮件");
    }

    onPublicClick() {
        console.log("打开公共功能");
    }

    // 右上角功能按钮
    onSignInClick() {
        console.log("打开签到");
    }

    onRechargeClick() {
        console.log("打开充值");
    }

    onActivityClick() {
        console.log("打开活动");
    }

    // 自动绑定按钮事件
    autoBindButtonEvents() {
        // 开宝箱按钮
        const openButton = this.node.getChildByPath('MiddleArea/ChestArea/OpenButton');
        if (openButton) openButton.on(Button.EventType.CLICK, this.onOpenChest, this);

        // 底部导航按钮
        const bagBtn = this.node.getChildByPath('BottomBar/BagBtn');
        const homeBtn = this.node.getChildByPath('BottomBar/HomeBtn');
        const reformBtn = this.node.getChildByPath('BottomBar/ReformBtn');

        if (bagBtn) bagBtn.on(Button.EventType.CLICK, this.onBagClick, this);
        if (homeBtn) homeBtn.on(Button.EventType.CLICK, this.onHomeClick, this);
        if (reformBtn) reformBtn.on(Button.EventType.CLICK, this.onReformClick, this);

        // 左上功能按钮
        const rankBtn = this.node.getChildByPath('LeftButtons/RankBtn');
        const pkBtn = this.node.getChildByPath('LeftButtons/PKBtn');
        const mailBtn = this.node.getChildByPath('LeftButtons/MailBtn');
        const publicBtn = this.node.getChildByPath('LeftButtons/PublicBtn');

        if (rankBtn) rankBtn.on(Button.EventType.CLICK, this.onRankClick, this);
        if (pkBtn) pkBtn.on(Button.EventType.CLICK, this.onPKClick, this);
        if (mailBtn) mailBtn.on(Button.EventType.CLICK, this.onMailClick, this);
        if (publicBtn) publicBtn.on(Button.EventType.CLICK, this.onPublicClick, this);

        // 右上功能按钮
        const signInBtn = this.node.getChildByPath('RightButtons/SignInBtn');
        const rechargeBtn = this.node.getChildByPath('RightButtons/RechargeBtn');
        const activityBtn = this.node.getChildByPath('RightButtons/ActivityBtn');

        if (signInBtn) signInBtn.on(Button.EventType.CLICK, this.onSignInClick, this);
        if (rechargeBtn) rechargeBtn.on(Button.EventType.CLICK, this.onRechargeClick, this);
        if (activityBtn) activityBtn.on(Button.EventType.CLICK, this.onActivityClick, this);
    }
}


/**********************************
 // 在其他脚本中使用数据服务的示例
const dataService = GameDataService.getInstance();

// 查询操作
const playerInfo = dataService.getPlayerInfo();
const inventory = dataService.getInventory();
const equipment = dataService.getEquipment();

// 更新操作
dataService.updatePlayerInfo({ gold: playerInfo.gold + 1000 });
dataService.addToInventory({
    id: "item_new",
    type: "material",
    name: "新物品",
    count: 5,
    maxStack: 20
});

// 删除操作
dataService.removeFromInventory("item_1001", 3);
 **********************************/